import { goto as __go } from '$app/navigation';
import { createMessage } from '$components/basic/message';
import { useUserstore } from '@/store';
import { get } from 'svelte/store';
import { persistentWritable } from './persist';

const whiteNameList = [
	'/',
	'/login',
	'/register',
	'/404',
	'/500',
	'/allproducts',
	'/calendar',
	'/detail',
	'/help',
	'/forget'
];

const recordRoute = () => {
	const current = persistentWritable('svelte:current-url', '/');
	current.set(window.location.pathname + window.location.search);
};

const intercept = (url: string) => {
	// 白名单
	if (whiteNameList.some((item) => item === url || (item !== '/' && url.startsWith(item)))) {
		return recordRoute(), url; // 记录当前路由
	}

	const userStore = useUserstore();
	const token = get(userStore.token);

	// token存在
	if (token) return recordRoute(), url;

	// token不存在
	// TODO: 拦截器
	createMessage({ type: 'light', message: 'please login first', duration: 2000 });
	return recordRoute(), '/login';
};

export const goto = (url: string) => {
	const result = intercept(url);

	return __go(result);
};

export const goBack = () => {
	const current = persistentWritable<string>('svelte:current-url', '');
	const url = get(current);
	current.set('');
	if (url === '/login') return __go('/account', { replaceState: true });
	if (url) return __go(url, { replaceState: true });
	if (window.history.length > 1) return window.history.back();
	return __go('/');
};
